package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

class MaximumDifferenceBetweenNodeAndAncestor{
    // 2024-03-10 12:02:44
    public static void main(String[] args) {
        Solution solution = new MaximumDifferenceBetweenNodeAndAncestor().new Solution();
    }
    
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int ans = 0;

    public int maxAncestorDiff(TreeNode root) {
        dfs(root, root.val, root.val);
        return ans;
    }

    /**
     * 维护当前节点的祖先的最大值和最小值
     * 向下遍历时，不断更新路径上的最大值和最小值
     * 到最后一个空节点时，其祖先的最大值-最小值就是该路径的最大差值
     */
    public void dfs(TreeNode root, int max, int min) {
        if (root == null) {
            ans = Math.max(ans, max - min);
            return;
        }
        min = Math.min(root.val, min);
        max = Math.max(root.val, max);
        dfs(root.left, max, min);
        dfs(root.right, max, min);
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}